const path = require('path');

const ctx = require.context('../views', true, /\.vue$/);

const routes = [];

const isHome = (path) => {
  path = path.toLowerCase();
  return path === 'index';
};

const isRoot = (path) => path.indexOf('/') === -1;

// 判断路径是否是出自 components 目录
const isComponent = (path) => {
  const ps = path.split('/');
  if (ps.length === 0) return false;
  return ps.reduce((result, item, index) => {
    const t = item.toLowerCase();
    if (t === 'components' && index < ps.length - 1) {
      return true;
    }
    return result;
  }, false);
};

let rootExists = false;

ctx.keys().forEach((file) => {
  let p = file.substring(1, file.length - 4);
  // 过滤掉 components 中的 vue 文件
  const isComponentsDir = isComponent(p);
  if (isComponentsDir) return;
  let root = isRoot(p.substring(1)) && isHome(p.substring(1));
  if (rootExists) root = false;
  const component = require(`@/views${file.substring(1)}`);
  const isScopeRoot = isHome(p.substring(p.lastIndexOf('/') + 1));
  if (!root && isScopeRoot) {
    p = p.substring(0, p.lastIndexOf('/'));
  }
  routes.push({
    path: root ? '/' : p,
    component: component.default,
  });
  if (root) {
    rootExists = true;
  }
});

export default routes;
